package com.mercury.core.manager;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author mercury
 * @create: 2021-03-03 14:43
 **/
@Slf4j
@Component
public class EasyExcelManager {

    public <E> List<E> parseExcel(InputStream inputStream, Class<E> clazz) {
        List<E> lists = new CopyOnWriteArrayList<>();
        // 解析每行结果在listener中处理
        EasyExcel.read(inputStream, clazz, new ExcelListener<>(lists)).sheet().doRead();
        return lists;
    }


    @EqualsAndHashCode(callSuper = true)
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Slf4j
    public static class ExcelListener<E> extends AnalysisEventListener<E> {

        /**
         * 自定义用于暂时存储data。
         * 可以通过实例获取该值
         */
        public List<E> excelList = new ArrayList<>();


        @Override
        public void invoke(E data, AnalysisContext context) {
            excelList.add(data);
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
            //数据解析完毕后的回调
            log.info("所有数据解析完成！");
        }
    }
}
